package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.SpecialPersonService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import cn.buildoncloud.labor.workermanapplet.util.OCRUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.nutz.dao.entity.Record;
import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/specialPerson")
public class SpecialPersonController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${webSystemIP}")
    private String webSystemIP;

    @Autowired
    private SpecialPersonService specialPersonService;

    /**
     * 获取
     * @param search
     * @param pId
     * @return
     */
    @RequestMapping("/listSpecialPerson")
    public Object listSpecialPerson(@RequestParam(required = false) String search, @RequestParam String pId){
        List<Record> specialPersons = null;
        try{
            specialPersons = specialPersonService.listSpecialPerson(search, Long.parseLong(pId));
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("服务器内部错误");
        }

        return Result.success("", specialPersons);
    }

    @RequestMapping("/getSpecialPerson")
    public Object getSpecialPerson(@RequestParam String id){

        Map specialPerson = null;
        try {
            specialPerson = specialPersonService.getSpecialPerson(Long.parseLong(id));
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("服务器内部错误");
        }

        return Result.success("", specialPerson);
    }

    @RequestMapping("/SpecialPersonOutProject")
    public Object SpecialPersonOutProject(@RequestParam String id){
        try {
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("personId", id);
            String result = HttpUtil.post(webSystemIP + "/business/specialPerson/del", parameterMap, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("服务器内部错误");
        }
    }

    @RequestMapping("/save")
    public Object saveManAndEnter(@RequestParam String name,
                                  @RequestParam String sex,
                                  @RequestParam String idCardNo,
                                  @RequestParam String nation,
                                  @RequestParam String birthDate,
                                  @RequestParam String address,
                                  @RequestParam String jobId,
                                  @RequestParam String tel,
                                  @RequestParam String projectId,
                                  @RequestParam String idCardPhotoPath,
                                  @RequestParam String headPhotoPath){
        try {
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("name", name);
            parameterMap.put("sex", sex);
            parameterMap.put("idCardNo", idCardNo);
            parameterMap.put("nation", nation);
            parameterMap.put("birthDate", birthDate);
            parameterMap.put("address", address);
            parameterMap.put("jobId", jobId);
            parameterMap.put("tel", tel);
            parameterMap.put("projectId", projectId);
            parameterMap.put("idCardPhotoPath", idCardPhotoPath);
            parameterMap.put("headPhotoPath", headPhotoPath);
            Map<String, Object> specialPersonExistence = null;
            //既然能走到这 证明 此 人员可以进场
            String result = HttpUtil.post(webSystemIP + "/business/specialPerson/add", parameterMap, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_FAILED_TO_ENTER);
        }

    }

    @RequestMapping("/listJob")
    public Object listJob(){
        List<Record> jobs = null;
        try{
            jobs = specialPersonService.listJob();
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }

        return Result.success("", jobs);
    }

    /**
     * 工程人员人脸对比方法
     * @param sId 工程人员ID
     * @param face 工程人员人脸对比BASE64
     * @return
     */
    @PostMapping("/faceComparison")
    public Object faceComparison(@RequestParam String sId,@RequestParam String face){
        // https://pre.buildoncloud.cn/workerman/face/getBase64ByFile
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 通过ID获取工程人员已录入人脸BASE64
            Map<String, Object> parameterMap1 = new HashMap<>();
            parameterMap1.put("id", sId);
            String base64File = HttpUtil.post(webSystemIP + "/face/getBase64BySpecialPersonFile", parameterMap1, 1000 * 60);
            Map<String, Object> readValueMap1 = objectMapper.readValue(base64File, HashMap.class);
            if (readValueMap1 == null){
                return Result.error(Constant.API_INTERFASE_ERROR);
            }
            Integer code = Integer.parseInt(readValueMap1.get("code").toString());
            if (code > 0) {
                return base64File;
            }
            String face1 = readValueMap1.get("data").toString();

            // 两张人脸进行对比返回相似码
            Map<String, Object> parameterMap2 = new HashMap<>();
            parameterMap2.put("face1", face1);
            parameterMap2.put("face2", face);
            String resultStr = HttpUtil.post(webSystemIP + "/face/base64ToJpgComparison", parameterMap2, 1000 * 60);

            Result result = objectMapper.readValue(resultStr, Result.class);

            if (result.getCode() > 0){
                return resultStr;
            }
            // 储存临时图片返回临时路径
            Map<String, Object> parameterMap3 = new HashMap<>();
            parameterMap3.put("imgStr", face);
            String faseFilePath = HttpUtil.post(webSystemIP + "/fileupload/base64toJpg", parameterMap3, 1000 * 60);

            Map<String, Object> readValueMap3 = objectMapper.readValue(faseFilePath, HashMap.class);
            if (readValueMap3 == null){
                return Result.error(Constant.API_INTERFASE_ERROR);
            }
            Integer code3 = Integer.parseInt(readValueMap3.get("code").toString());
            if (code3 > 0){
                return faseFilePath;
            }
            String photoPath = readValueMap3.get("data").toString();


            Map<String, Object> headPhotoMap =  specialPersonService.getSpecialPersonHeadPhotoById(Long.parseLong(sId));
            Double data = (Double) result.getData();
            Map<String, Object> map = new HashMap<>();
            map.put("difference", data);
            map.put("face1_photo_id", headPhotoMap.get("head_photo_id"));
            map.put("photoPath", photoPath);

            result.setData(map);
            return result;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return Result.error(Constant.API_INTERFASE_ERROR);
    }


    @PostMapping("/updateFaceBySpecialPerson")
    public Object updateFaceByWorkerMan(@RequestParam String sId,@RequestParam String photoPath){
        try{
            Map<String, Object> parameterMap2 = new HashMap<>();
            parameterMap2.put("personId", sId);
            parameterMap2.put("photoPath", photoPath);
            String result = HttpUtil.post(webSystemIP + "/business/specialPerson/updPhoto", parameterMap2, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return Result.error(Constant.API_INTERFASE_ERROR);
    }

    /**
     * 工程人员身份证上传接口
     * @param base64File
     * @param pId
     * @return
     */
    @RequestMapping("/uploadIdCard")
    public Object uploadIdCard(@RequestParam String base64File, @RequestParam String pId){
        //face/decorativeIdCardPhoto photo

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = new HashMap<>();
            Result result = OCRUtil.ocrIdCard(base64File);

            //是否图片正确 且有返回值
            if(result.getData()!=null){
                //获取 data
                String dataJsonStr = objectMapper.writeValueAsString(result.getData());
                try{
                    data= objectMapper.readValue(dataJsonStr, HashMap.class);

                    if(data.get("idCardInfo")!=null){
                        //获取身份证信息
                        HashMap<String ,Object> idCardInfo = (HashMap) data.get("idCardInfo");
                        //获取身份证号
                        String idCardNo = (String) idCardInfo.get("id");
                        //根据身份证号 查询该项目中是否已有此工程人员 且未退场
                       Map<String,Object> specialPerson= specialPersonService.selectSepcialPersonByPidAndIdCardNo(pId,idCardNo);
                       if(specialPerson!=null){

                           return Result.error("工程人员已进场，请勿重复进场");
                       }

                    }


                }
                catch (JsonMappingException e){}
                catch (JsonParseException e){}
                catch (IOException e){}


            }


            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("photo", base64File);
            String idCardPhotoResult = HttpUtil.post(webSystemIP + "/face/decorativeIdCardPhoto", parameterMap);

            Map<String, Object> idCardPhotoResultMap = objectMapper.readValue(idCardPhotoResult , HashMap.class);

            if (idCardPhotoResultMap.get("code") == null){
                return Result.error(Constant.API_NETWORK_ANOMALY);
            }

            Integer codeNum = Integer.parseInt(idCardPhotoResultMap.get("code").toString());
            if (codeNum != 0){
                return idCardPhotoResult;
            }
            Map<String, Object> dataMap = (Map) idCardPhotoResultMap.get("data");

            data.put("idCardPhoto", dataMap.get("ID_CARD_PHOTO").toString());
            data.put("idHeadPath", dataMap.get("ID_HEAD_PATH").toString());

            result.setData(data);
            return result;
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

}
